package com.school.controller;

import com.school.entity.ClassEntity;
import com.school.entity.Student;
import com.school.service.ClassService;
import com.school.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @Autowired
    private ClassService classService;

    /**
     * 获取学生列表
     */
    @GetMapping("/list")
    public List<Map<String, Object>> list(
            @RequestParam(required = false) Long classId,
            @RequestParam(required = false) String keyword) {

        List<Student> students = studentService.search(classId, keyword);

        // 获取所有班级信息，用于转换班级ID为班级名称
        Map<Long, String> classMap = classService.findAll().stream()
                .collect(Collectors.toMap(ClassEntity::getId, ClassEntity::getName));

        // 转换为前端需要的格式
        return students.stream().map(student -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", student.getId());
            map.put("studentId", student.getStudentId());
            map.put("name", student.getName());
            map.put("gender", student.getGender());
            map.put("phone", student.getPhone());
            map.put("classId", student.getClassId());
            map.put("className", classMap.getOrDefault(student.getClassId(), ""));
            return map;
        }).collect(Collectors.toList());
    }

    /**
     * 添加学生
     */
    @PostMapping("/add")
    public Map<String, Object> add(@RequestBody Student student) {
        Map<String, Object> result = new HashMap<>();

        // 检查学号是否已存在
        if (studentService.findByStudentId(student.getStudentId()).isPresent()) {
            result.put("success", false);
            result.put("message", "学号已存在");
            return result;
        }

        // 检查班级是否存在
        if (student.getClassId() != null && classService.findById(student.getClassId()).isEmpty()) {
            result.put("success", false);
            result.put("message", "所选班级不存在");
            return result;
        }

        // 创建学生并自动创建对应的用户账号
        studentService.createStudentWithUser(student);

        result.put("success", true);
        return result;
    }

    /**
     * 编辑学生
     */
    @PostMapping("/edit")
    public Map<String, Object> edit(@RequestBody Student student) {
        Map<String, Object> result = new HashMap<>();

        // 检查学生是否存在
        Optional<Student> existingStudent = studentService.findById(student.getId());
        if (existingStudent.isEmpty()) {
            result.put("success", false);
            result.put("message", "学生不存在");
            return result;
        }

        // 检查学号是否与其他学生重复
        Optional<Student> studentWithSameId = studentService.findByStudentId(student.getStudentId());
        if (studentWithSameId.isPresent() && !studentWithSameId.get().getId().equals(student.getId())) {
            result.put("success", false);
            result.put("message", "学号已被其他学生使用");
            return result;
        }

        // 检查班级是否存在
        if (student.getClassId() != null && classService.findById(student.getClassId()).isEmpty()) {
            result.put("success", false);
            result.put("message", "所选班级不存在");
            return result;
        }

        // 更新学生信息
        Student existing = existingStudent.get();
        existing.setName(student.getName());
        existing.setGender(student.getGender());
        existing.setPhone(student.getPhone());
        existing.setClassId(student.getClassId());

        studentService.save(existing);

        result.put("success", true);
        return result;
    }

    /**
     * 删除学生
     */
    @PostMapping("/delete")
    public Map<String, Object> delete(@RequestBody Map<String, Object> param) {
        Map<String, Object> result = new HashMap<>();

        // 支持通过ID或学号删除
        if (param.containsKey("id")) {
            Long id = Long.valueOf(param.get("id").toString());
            if (studentService.findById(id).isEmpty()) {
                result.put("success", false);
                result.put("message", "学生不存在");
                return result;
            }
            studentService.deleteById(id);
        } else if (param.containsKey("studentId")) {
            String studentId = param.get("studentId").toString();
            if (studentService.findByStudentId(studentId).isEmpty()) {
                result.put("success", false);
                result.put("message", "学生不存在");
                return result;
            }
            studentService.deleteByStudentId(studentId);
        } else {
            result.put("success", false);
            result.put("message", "参数错误");
            return result;
        }

        result.put("success", true);
        return result;
    }

    /**
     * 获取学生详情
     */
    @GetMapping("/detail")
    public Map<String, Object> detail(@RequestParam Long id) {
        Map<String, Object> result = new HashMap<>();

        Optional<Student> student = studentService.findById(id);
        if (student.isEmpty()) {
            result.put("success", false);
            result.put("message", "学生不存在");
            return result;
        }

        result.put("success", true);
        result.put("data", student.get());

        // 如果有班级ID，获取班级名称
        if (student.get().getClassId() != null) {
            classService.findById(student.get().getClassId()).ifPresent(classEntity -> {
                result.put("className", classEntity.getName());
            });
        }

        return result;
    }
}